import { FileMainProps } from "@/types";
import { Input, Tooltip, Tree } from "antd";
import { deepClone, LockState } from "@meta2d/core";
import styles from "@/layout/Configuration/Configuration.module.scss";
import {
  EyeInvisibleOutlined,
  EyeOutlined,
  FileImageOutlined,
  FolderOutlined,
} from "@ant-design/icons";
import React, { useEffect, useState } from "react";
import { getNextLocked, lockedMap } from "@/config/lockedMap.tsx";

function TreeName({
  item,
  updatePensData,
}: {
  item: any;
  updatePensData: () => void;
}) {
  const iconStyle: React.CSSProperties = {
    marginRight: 5,
    fontSize: 14,
  };
  const [locked, setLocked] = useState(LockState.None);
  const [isEdit, setIsEdit] = useState(false);
  const [name, setName] = useState("");
  useEffect(() => {
    if (item.locked != undefined) {
      setLocked(item.locked);
    }
    if (item.description == undefined) {
      setName(item.name);
    } else {
      setName(item.description);
    }
  }, []);
  const setPenVisible = (arg: any, visible: boolean) => {
    window.meta2d.setValue({
      id: arg.id,
      visible,
    });
    if (arg.children && arg.children.length > 0) {
      for (let i = 0; i < arg.children.length; i++) {
        setPenVisible(arg.children[i], visible);
      }
    }
  };
  const setPenLocked = () => {
    let l = getNextLocked(locked);
    window.meta2d.setValue({
      id: item.id,
      locked: l,
    });
    setLocked(() => l as LockState);
  };
  const activePen = () => {
    const targetPen = window.meta2d.findOne(item.id);
    if (targetPen != undefined) {
      window.meta2d.active([targetPen]);
    }
    window.meta2d.render();
  };
  const getColor = (): string => {
    const targetPen = window.meta2d.findOne(item.id);
    if (targetPen && targetPen.calculative) {
      let isActive =
        targetPen.calculative.active == undefined
          ? false
          : targetPen.calculative.active;
      return isActive ? "#1890ff" : "#ffffff";
    } else {
      return "#ffffff";
    }
  };
  const onEditBlur = () => {
    setIsEdit(false);
    if (name.trim() == "") {
      if (item.description == undefined) {
        setName(item.name);
      } else {
        setName(item.description);
      }
      return;
    }
    window.meta2d.setValue({
      id: item.id,
      description: name,
    });
  };
  return (
    <div
      className={"flex between"}
      title={`id: ${item.id}\nname: ${item.name}`}
    >
      <div>
        <span style={iconStyle}>
          {item.children.length > 0 ? (
            <FolderOutlined />
          ) : (
            <FileImageOutlined />
          )}
        </span>
        <span
          style={{
            fontSize: 14,
            color: getColor(),
          }}
          className={styles.penName}
          onClick={activePen}
          onDoubleClick={() => {
            setIsEdit((v) => !v);
          }}
        >
          {isEdit ? (
            <Input
              placeholder="请输入"
              autoFocus
              className={styles.editInput}
              value={name}
              size={"small"}
              onChange={(e) => {
                setName(e.target.value);
              }}
              onBlur={onEditBlur}
            />
          ) : (
            <>{name}</>
          )}
        </span>
      </div>
      {!isEdit && (
        <div>
          <Tooltip
            placement="top"
            title={lockedMap[locked as keyof typeof lockedMap].desc}
          >
            <span style={iconStyle} onClick={setPenLocked}>
              {lockedMap[locked as keyof typeof lockedMap].icon}
            </span>
          </Tooltip>

          {item.visible ? (
            <EyeOutlined
              style={iconStyle}
              onClick={() => {
                setPenVisible(item, false);
                updatePensData();
              }}
            />
          ) : (
            <EyeInvisibleOutlined
              style={iconStyle}
              onClick={() => {
                setPenVisible(item, true);
                updatePensData();
              }}
            />
          )}
        </div>
      )}
    </div>
  );
}

export function LayerStructure(props: FileMainProps) {
  const [treeData, setTreeData] = useState<any[]>([]);
  const [_dateNow, setDateNow] = useState(+new Date());
  const getTreeData = () => {
    setTreeData(() => recursiveToTree(deepClone(props.storeData.pens)));
    setDateNow(() => +new Date());
  };

  useEffect(() => {
    window.meta2d.on("active", () => {
      getTreeData();
    });
    getTreeData();
  }, []);
  function recursiveToTree(data: any[]) {
    if (data == undefined) return [];
    const res: any[] = [];
    data.forEach((item) => {
      item.children = [];
      item.title = (
        <TreeName
          updatePensData={() => {
            setTreeData(() => []);
            getTreeData();
          }}
          item={item}
        />
      );
      if (item.visible == undefined) {
        window.meta2d.setValue({
          id: item.id,
          visible: true,
        });
      }
      if (item.visible == undefined) {
        window.meta2d.setValue({
          id: item.id,
          locked: LockState.None,
        });
      }

      const parent = data.find((node) => node.id === item.parentId);
      if (parent) {
        parent.children.push(item);
      } else {
        // * 根节点
        res.push(item);
      }
    });
    return res;
  }

  return (
    <>
      <Tree
        showLine
        style={{ marginTop: 5 }}
        blockNode
        fieldNames={{ title: "title", key: "id", children: "children" }}
        treeData={treeData}
      />
    </>
  );
}
